import { axiosInstance } from './axios-instance';

export interface CreateExamDto {
  title: string;
  description: string;
  startTime: string;
  endTime: string;
  duration: number;
  totalScore: number;
  passingScore: number;
  userId: number;
}

export interface GenerateQuestionsDto {
  count: number;
  subject: string;
}

export interface Exam {
  id: number;
  title: string;
  description: string;
  startTime: string;
  endTime: string;
  duration: number;
  totalScore: number;
  passingScore: number;
  userId: number;
  createdAt?: string;
  updatedAt?: string;
}

export const examApi = {
  // 获取所有考试
  getAll: async () => {
    const response = await axiosInstance.get<Exam[]>('/exams');
    return response.data;
  },

  // 获取单个考试
  getById: async (id: number) => {
    const response = await axiosInstance.get<Exam>(`/exams/${id}`);
    return response.data;
  },

  // 创建考试
  create: async (exam: CreateExamDto) => {
    const response = await axiosInstance.post<Exam>('/exams', exam);
    return response.data;
  },

  // 更新考试
  update: async (id: number, exam: Partial<CreateExamDto>) => {
    const response = await axiosInstance.patch<Exam>(`/exams/${id}`, exam);
    return response.data;
  },

  // 删除考试
  delete: async (id: number) => {
    const response = await axiosInstance.delete<Exam>(`/exams/${id}`);
    return response.data;
  },

  // 获取考试状态
  getStatus: async (id: number) => {
    const response = await axiosInstance.get<{ status: 'NOT_STARTED' | 'IN_PROGRESS' | 'ENDED' }>(`/exams/${id}/status`);
    return response.data;
  },

  // 生成随机题目
  generateQuestions: async (id: number, data: GenerateQuestionsDto) => {
    const response = await axiosInstance.post<Exam>(`/exams/${id}/generate-questions`, data);
    return response.data;
  },

  // 检查考试访问权限
  checkAccess: async (id: number) => {
    const response = await axiosInstance.get<{ canAccess: boolean }>(`/exams/${id}/check-access`);
    return response.data;
  },

  // 获取可参加的考试列表
  getAvailableExams: async () => {
    const response = await axiosInstance.get<Exam[]>('/exams/available');
    return response.data;
  },
  // 提交考试答案
  submitExam: async (id: number, data: { answers: { questionId: number; answer: string }[] }) => {
    const response = await axiosInstance.post<{ score: number }>(`/exams/${id}/submit`, data);
    return response.data;
  },
  // 获取学生考试结果
  getStudentExamResults: async () => {
    const response = await axiosInstance.get('/exams/student/results');
    return response.data;
  },
};